<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button plain icon="Download" @click="handleImport">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="Delete" @click="handleDelete">删除</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="tableData" stripe @selection-change="handleSelectionChange" :span-method="objectSpanMethod" row-key="id" :header-cell-style="headerMethod">
      <el-table-column type="selection" width="55" align="center" prop="id" :reserve-selection="true" />
      <!-- <el-table-column label="序号" type="index" align="center" width="55"></el-table-column> -->
      <el-table-column label="序号" prop="number" align="center" width="55"></el-table-column>
      <el-table-column label="台站名称" prop="stationName" align="center"></el-table-column>
      <el-table-column label="台站" align="center">
        <el-table-column label="经度" align="center">
            <el-table-column prop="stationLongitude" label="（°E）" width="120" align="center"/>
        </el-table-column>
      </el-table-column>
      <el-table-column label="台站" align="center">
        <el-table-column label="纬度" align="center">
            <el-table-column prop="stationLatitude" label="（°N）" width="120" align="center"/>
        </el-table-column>
      </el-table-column>
      <el-table-column label="震中距（km）" prop="epicenterDistance" align="center"></el-table-column>
      <el-table-column label="震中方位角" prop="epicenterAzimuth" align="center"></el-table-column>
      <el-table-column label="PGA（cm/s/s）" align="center">
        <el-table-column align="center">
          <el-table-column prop="pgaEw" label="EW" width="120" align="center"/>
          <el-table-column prop="pgaNs" label="NS" width="120" align="center"/>
          <el-table-column prop="pgaUd" label="UD" width="120" align="center"/>
        </el-table-column>
      </el-table-column>
      <el-table-column label="PGV（cm/s/s）" align="center">
        <el-table-column align="center">
          <el-table-column prop="pgvEw" label="EW" width="120" align="center"/>
          <el-table-column prop="pgvNs" label="NS" width="120" align="center"/>
          <el-table-column prop="pgvUd" label="UD" width="120" align="center"/>
        </el-table-column>
      </el-table-column>
      <el-table-column label="仪器烈度" prop="instrumentIntensity" align="center"></el-table-column>
      <el-table-column label="备注" prop="remark" align="center"></el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
      @pagination="getTable" />

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <p></p>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :before-upload="handleFileBeforeUpload" :on-progress="handleFileUploadProgress"
        :on-error="handleFileUploadError" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate('仪器烈度导入模板.xlsx')">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button plain @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="instrumentIntensity">
import { getToken } from "@/utils/auth";
import { getList, deleteList } from '@/api/disasterManage/instrumentIntensity'
import { dataMethod } from '@/utils/spanTable.js'
import useEventStore from "@/store/modules/event";

const { proxy } = getCurrentInstance();
const currentEvent = computed(() => useEventStore().currentEvent);
let loading = ref(false)
let tableData = ref([])
let queryParams = ref({
  page: 1,
  rows: 10
})
let total = ref(0)
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  headers: { token: "token " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/instrumentIntensity/importExcel"
});
let ids = ref([])
const structureType = [
  {name: 'I类', value: '0'},
  {name: 'II类', value: '1'},
  {name: 'III-1类', value: '2'},
  {name: 'III-2类', value: '3'},
  {name: 'Ⅳ类', value: '4'},
  {name: 'V-1类', value: '5'},
  {name: 'V-2类', value: '6'},
  {name: 'V-3类', value: '7'},
  {name: 'Ⅵ类', value: '8'},
  {name: 'Ⅶ类', value: '9'},
]
const spanObj = ref();
// 合并列
function objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
  const _row = spanObj.value[column.property] ? spanObj.value[column.property][rowIndex] : 1;
  const _col = _row > 0 ? 1 : 0;
  return {
    rowspan: _row,
    colspan: _col,
  }
}

function headerMethod({ row, column, rowIndex, columnIndex }) {
  if (rowIndex === 0) {
    if(columnIndex === 7 || columnIndex === 8){
      row[columnIndex].rowSpan = 2
      row[columnIndex].colSpan = 3
    }
  }
}

const getTable = () => {
  loading.value = true
  let xsemId = currentEvent.value.id;
  getList(queryParams.value,xsemId).then(res => {
    loading.value = false
    tableData.value = res.data.rows
    total.value = res.data.total
    spanObj.value = dataMethod(tableData.value, ['id','code','boundary','reliability']);
  })
}

function handleImport() {
  upload.title = "导入";
  upload.open = true;
}

function handleFileBeforeUpload(file) {
  proxy.$modal.loading("正在上传文件，请稍候...");
  return true
}

const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

function handleFileUploadError(err) {
  proxy.$modal.closeLoading();
  proxy.$modal.msgError("上传文件失败");
}

const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$modal.closeLoading();
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$modal.msgSuccess("上传成功");
  getTable();
};

function importTemplate(name) {
  proxy.downloadTemplate("/template/download", {
    fileName: name
  }, name);
};

function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
}

function handleDelete(row) {
  const id = ids.value;
  if(ids.value.length === 0) {
    proxy.$modal.msgWarning('请至少选择一条数据！');
    return;
  }
  proxy.$modal.confirm('是否确认删除勾选的遥感数据？').then(function () {
    return deleteList(id.join(','))
  }).then((res) => {
    getTable();
    proxy.$modal.msgSuccess('删除成功');
  }).catch(() => { });
}

//获取当前事件
watch(() => currentEvent.value, val => {
  if(val && val.id){
    getTable();//初始化
  }
},{ deep: true, immediate: true });
</script>
